import 'package:m_todo/domain/entity/account_entity.dart';
import 'package:m_todo/domain/store/base_account_store.dart';

import 'config_file_util.dart';

class FileAccountStore extends BaseAccountStore {
  final ConfigFileUtil _configFileUtil = ConfigFileUtil();

  @override
  Future<void> clearLoginAccount() async {
    await _configFileUtil.updateConfig((config) => config.loginAccount = null);
  }

  @override
  Future<AccountEntity?> getLoginAccount() async {
    var config = await _configFileUtil.getConfig();
    return config.loginAccount;
  }

  @override
  Future<AccountEntity?> queryAccountByName(String name) async {
    try {
      var config = await _configFileUtil.getConfig();
      var account = config.accounts?.firstWhere((element) => element.name == name);
      return account;
    } catch (e) {
      return null;
    }
  }

  Future<void> init(List<AccountEntity> accountEntity, {AccountEntity? login}) async {
    // 检查账号规范
    accountEntity.forEach((element) {
      if (element.name == null || element.password == null || element.password?.length == 0) {
        throw Future.error('register 账号不符合规范 ${element.name} ${element.password}');
      }
    });

    await _configFileUtil.updateConfig((config) {
      if (config.accounts == null) {
        config.accounts = [];
      }
      config.accounts!.clear();
      config.accounts!.addAll(accountEntity);

      config.loginAccount = login;
    });
  }

  @override
  Future<void> saveLoginAccount(AccountEntity accountEntity) async {
    await _configFileUtil.updateConfig((config) => config.loginAccount = accountEntity);
  }
}
